
import pandas as pd
import json
from glom import glom

def fun1():
    df = pd.read_json('../sites.json')
    print(df.to_string())

def fun2():
    data = [
        {
          "id": "A001",
          "name": "菜鸟教程",
          "url": "www.runoob.com",
          "likes": 61
        },
        {
          "id": "A002",
          "name": "Google",
          "url": "www.google.com",
          "likes": 124
        },
        {
          "id": "A003",
          "name": "淘宝",
          "url": "www.taobao.com",
          "likes": 45
        }
    ]
    df = pd.DataFrame(data)
    print(df)

def fun3():
    # 字典格式的JSON
    s = {
        "col1": {"row1": 1, "row2": 2, "row3":3},
        "col2": {"row1": "x", "row2":"y", "row3":"z"}
    }

    df = pd.DataFrame(s)
    print(df)

def fun4():
    URL = 'https://static.jyshare.com/download/sites.json'
    df = pd.read_json(URL)
    print(df)

def fun5():
    df = pd.read_json('../nested_list.json')
    print(df)

# json_normalize() 方法将内嵌的数据完整的解析出来
def fun6():
    # 使用Python JSON模块载入数据
    with open('../nested_list', 'r') as f:
        data = json.load(f.read())

    # 展平数据
    df_nested_list = pd.json_normalize(data, record_path=['students'])
    print(df_nested_list)

def fun7():
    with open('../nested_list.json', 'r') as f:
        data = json.loads(f.read())

    df_nested_list = pd.json_normalize(data,
                                       record_path=['students'],
                                       meta=['school_name', 'class'])
    print(df_nested_list)

def fun8():
    with open('../nested_mix.json', 'r') as f:
        data = json.loads(f.read())
    df = pd.json_normalize(data
                           , record_path=['students'],
                           meta=[
                               'class',
                               ['info', 'president'],
                               ['info', 'contacts', 'tel']
                           ])
    print(df)

def fun9():
    df = pd.read_json('../nested_deep.json')
    data = df['students'].apply(lambda row: glom(row, 'grade.math'))
    print(data)


if __name__ == '__main__':
    fun9()